package edu.service.impl;

import edu.service.StudentService;
import edu.vo.Student;
import edu.repository.StudentRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class StudentServiceImpl implements StudentService {

    private final StudentRepository studentRepository;

    public StudentServiceImpl(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;
    }

    @Override
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }

    @Override
    public Optional<Student> getStudentById(Integer id) {
        return studentRepository.findById(id);
    }

    @Override
    public List<Student> getAllStudents() {
        return studentRepository.findAll();
    }

    @Override
    public void deleteStudentById(Integer id) {
        studentRepository.deleteById(id);
    }

    @Override
    public Student updateStudent(Integer id, Student student) {
        return studentRepository.findById(id)
                .map(existingStudent -> {
                    existingStudent.setUserName(student.getUserName());
                    existingStudent.setName(student.getName());
                    existingStudent.setSex(student.getSex());
                    existingStudent.setBirthday(student.getBirthday());
                    existingStudent.setPhone(student.getPhone());
                    existingStudent.setClazz(student.getClazz());
                    existingStudent.setMotto(student.getMotto());
                    return studentRepository.save(existingStudent);
                })
                .orElse(null);
    }
}